package com.allenkerr.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Created by 小柯 on 17/6/22.
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {

    private Converter<Object, byte[]> serializingConverter = new SerializingConverter();

    private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();

    static final byte[] EMPTY_ARRAY = new byte[0];

    /**
     * 序列化
     */
    @Override
    public byte[] serialize(Object object) throws SerializationException {
        if (object == null)
            return EMPTY_ARRAY;

        try {
            return serializingConverter.convert(object);
        } catch (Exception e) {
            e.printStackTrace();
            return EMPTY_ARRAY;
        }
    }

    /**
     * 反序列化
     */
    @Override
    public Object deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0)
            return null;

        try {
            return deserializingConverter.convert(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
